// localStorage h5 本地存储处理
export const setCache = (key, value) => {
  const _value = value instanceof Object ? JSON.stringify(value) : value
  localStorage.setItem(key, _value)
}

export const getCacheByKey = (key) => {
  return localStorage.getItem(key)
}

export const removeCacheByKey = (key) => {
  localStorage.removeItem(key)
}

export const clearCacheAll = () => {
  localStorage.clear()
}

// 歌曲播放记录缓存
export const getMusicHistoryPlayList = () => {
  const key = 'PLAY_MUSIC_LIST'
  let res = getCacheByKey(key)
  // eslint-disable-next-line no-console
  console.log(typeof res)
  if (!res) {
    res = []
  } else {
    res = JSON.parse(res)
  }
  return res
}
export const savePlayMusicHistory = (id, name, author) => {
  const key = 'PLAY_MUSIC_LIST'
  const list = getMusicHistoryPlayList()
  if (list.length <= 0) {
    setCache(key, [{ id, name, author }])
  } else {
    const ids = list.map(item => item.id)
    const has = ids.includes(id)
    if (!has) {
      list.unshift({ id, name, author })
      setCache(key, list)
    }
  }
}

// 历史搜索
export const getSearchHistory = () => {
  const key = 'SEARCH_LIST'
  let res = getCacheByKey(key)
  if (!res) {
    res = []
  } else {
    res = JSON.parse(res)
  }
  return res
}
export const saveSearchHistory = (word) => {
  const key = 'SEARCH_LIST'
  let list = getSearchHistory()
  if (list.length <= 0) {
    setCache(key, [word])
  } else {
    const has = list.includes(word)
    list.unshift(word)
    if (has) {
      // 存在,移到最前面
      list = Array.from(new Set(list))
    }
    setCache(key, list)
  }
}
export const clearSearchHistory = () => {
  const key = 'SEARCH_LIST'
  removeCacheByKey(key)
}

// 上次搜索的歌单记录 保存上次搜索的关键字,及歌单tab滚动的位置
// 只存一条
export const getSearchPlayList = () => {
  const key = 'CACHE_SEARCH_PLAY_LIST'
  let res = getCacheByKey(key)
  if (!res) {
    res = {}
  } else {
    res = JSON.parse(res)
  }
  return res
}
export const saveSearchPlayList = (word, listOffset, offsety = 0) => {
  const key = 'CACHE_SEARCH_PLAY_LIST'
  if (word) {
    setCache(key, { word, listOffset, offsety })
  }
}
/** 清除上次搜索缓存的歌单记录 */
export const clearLastSearchPlayList = () => {
  const key = 'CACHE_SEARCH_PLAY_LIST'
  removeCacheByKey(key)
}
